package com.gs.douban.gui;

import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.awt.Toolkit;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JButton;

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.gs.douban.model.UserInfo;
import com.gs.douban.utils.HttpClientUtil;
import com.gs.douban.utils.JsonFormatTool;
import com.gs.douban.utils.PasswordUtil;
import com.gs.douban.worker.LikedSongDownloader;
import com.gs.log.TextAreaLogAppender;
import com.mpatric.mp3agic.NotSupportedException;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JCheckBox;
import java.awt.Font;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class NewMain {

	private static JFrame frame;
	private JTextField usernametf;
	private JPasswordField passwordtf;
	private JTextField pathtf;
	private Thread t;
	private JFileChooser fDialog;
	private JLabel statel;
	private JLabel label;
	private JLabel userinfol;
	private Logger LOG = Logger.getLogger(NewMain.class);
	private static JTextArea textArea;
	private static JScrollPane scrollPane;
	private JCheckBox checkBox;
	private static JTabbedPane tabbedPane;
	private static JPanel panel_1;
	private static JTextField querytf;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					NewMain window = new NewMain();
					window.frame.setVisible(true);
					Thread t2;  
			         t2 = new TextAreaLogAppender(textArea, scrollPane);
			         
			         
			         
			         
			         t2.start();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public NewMain() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 882, 428);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		tabbedPane.setBounds(5, 8, 856, 377);
		frame.getContentPane().add(tabbedPane);
		panel_1 = new JPanel();
        tabbedPane.addTab("搜索歌曲", null, panel_1, null);
        panel_1.setLayout(null);
        
        querytf = new JTextField();
        querytf.setBounds(316, 128, 163, 21);
        panel_1.add(querytf);
        querytf.setColumns(10);
        
        JButton btnNewButton = new JButton("搜索");
        btnNewButton.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent arg0) {
        		try {
					Desktop.getDesktop().browse(new URI("http://music.baidu.com/search?key="+querytf.getText()));
				} catch (IOException e) {
					LOG.error(e.getMessage());
					e.printStackTrace();
				} catch (URISyntaxException e) {
					LOG.error(e.getMessage());
					e.printStackTrace();
				}
        	}
        });
        btnNewButton.setBounds(338, 174, 93, 23);
        panel_1.add(btnNewButton);
        
        JLabel label_1 = new JLabel("歌曲名");
        label_1.setBounds(239, 131, 54, 15);
        panel_1.add(label_1);
		JPanel panel = new JPanel();
		tabbedPane.addTab("下载红心歌曲", null, panel, null);
		panel.setLayout(null);

		usernametf = new JTextField();
		usernametf.setBounds(123, 31, 169, 21);
		panel.add(usernametf);
		usernametf.setColumns(10);

		JLabel lblNewLabel = new JLabel("用户名");
		lblNewLabel.setBounds(11, 34, 54, 15);
		panel.add(lblNewLabel);

		JLabel lblNewLabel_1 = new JLabel("密码");
		lblNewLabel_1.setBounds(11, 105, 54, 15);
		panel.add(lblNewLabel_1);

		passwordtf = new JPasswordField();
		passwordtf.setBounds(123, 102, 169, 21);
		panel.add(passwordtf);

		pathtf = new JTextField();
		pathtf.setBounds(123, 178, 169, 21);
		panel.add(pathtf);
		pathtf.setColumns(10);
		label = new JLabel("存放路径");
		label.setBounds(11, 181, 54, 15);
		panel.add(label);

		checkBox = new JCheckBox("获取红心列表?");
		checkBox.setBounds(123, 217, 171, 23);
		panel.add(checkBox);
		
		JButton browserb = new JButton("浏览...");
		browserb.setBounds(298, 178, 75, 23);
		panel.add(browserb);
		
				statel = new JLabel("State");
				statel.setBounds(0, 307, 356, 15);
				panel.add(statel);
				
						JButton btnNewButton_1 = new JButton("开始");
						btnNewButton_1.setBounds(123, 273, 67, 23);
						panel.add(btnNewButton_1);
						
								userinfol = new JLabel("User Info");
								userinfol.setBounds(0, 248, 365, 15);
								panel.add(userinfol);
								
										JButton stopb = new JButton("停止");
										stopb.setBounds(225, 273, 67, 23);
										panel.add(stopb);
										
										scrollPane = new JScrollPane();
										scrollPane.setBounds(377, 0, 479, 377);
										panel.add(scrollPane);
										
										textArea = new JTextArea();
										textArea.setFont(new Font("微软雅黑", Font.PLAIN, 15));
										scrollPane.setViewportView(textArea);
										stopb.addActionListener(new ActionListener() {
											public void actionPerformed(ActionEvent arg0) {
												t.interrupted();
												t.stop();
												statel.setText("已停止");
											}
										});
						btnNewButton_1.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent arg0) {
								t = new Thread(new Runnable() {
									public void run() {
										try {
											FileUtils.writeStringToFile(new File("user.inf"), new Gson().toJson(new UserInfo(usernametf.getText(),new String(PasswordUtil.encrypt(new String(passwordtf.getPassword()), "940409")),pathtf.getText())));
										} catch (IOException e3) {
											e3.printStackTrace();
										}
										statel.setText("正在获取验证码,请稍候.");
										HttpClientUtil hc = new HttpClientUtil();
										String codeid = null;
										try {
											codeid = hc.get("http://douban.fm/j/new_captcha")
													.replaceAll("\"", "");
										} catch (HttpException e1) {
											e1.printStackTrace();
										} catch (IOException e1) {
											e1.printStackTrace();
										}
										String code = null;
										try {
											code = JOptionPane.showInputDialog(null,
													new ImageIcon(new URL(
															"http://douban.fm/misc/captcha?size=m&id="
																	+ codeid)));
										} catch (HeadlessException e2) {
											e2.printStackTrace();
										} catch (MalformedURLException e2) {
											e2.printStackTrace();
										}
										statel.setText("正在登录...");
										Map<String, String> m = new HashMap<String, String>();
										m.put("source", "radio");
										m.put("alias", usernametf.getText());
										m.put("form_password",
												new String(passwordtf.getPassword()));
										m.put("captcha_solution", code);
										m.put("captcha_id", codeid);
										m.put("remember", "on");
										m.put("task", "sync_channel_list");
										String r = null;
										String coo = null;
										try {
											r = hc.post("http://douban.fm/j/login", m,
													"flag=\"ok\"; fmNlogin=\"y\";");
											LOG.debug(r);
											coo = (hc.getCookie());
										} catch (HttpException e1) {
											e1.printStackTrace();
										} catch (IOException e1) {
											e1.printStackTrace();
										}
										if (!new File(pathtf.getText()+"//list.txt").exists()&&checkBox.isSelected()) {
											LOG.info("正在生成红心歌曲列表,请稍候在"+pathtf.getText()+"//list.txt中查看列表");
											Pattern p0 = Pattern
													.compile("ck\":\"([\\s\\S]*?)\"");
											Matcher ma0 = p0.matcher(r);
											String ck = null;
											if (ma0.find()) {
												ck = ma0.group(1);
											}
											try {
												LikedSongDownloader.getList(coo, ck,
														pathtf.getText());
											} catch (HttpException e1) {
												e1.printStackTrace();
											} catch (IOException e1) {
												e1.printStackTrace();
											}
											LOG.info("列表生成完毕");
										}else if(new File(pathtf.getText()+"//list.txt").exists()&&checkBox.isSelected()){
											LOG.info("列表文件已存在,如需重新加载,请手动删除列表文件");
										}
										Pattern p = Pattern.compile("\"name\":\"([\\s\\S]*?)\"");
										Matcher ma = p.matcher(r);
										if(ma.find()){
											userinfol.setText("欢迎"+ma.group(1));
										}else{
											userinfol.setText("登录失败");
											LOG.info("登录失败,请核对信息后重试");
											statel.setText("登录失败,请核对信息后重试");
											return;
										}
										Pattern p2 = Pattern.compile("liked\":([\\s\\S]*?),");
										Matcher ma2 = p2.matcher(r);
										if(ma2.find()){
											userinfol.setText(usernametf.getText()+"红心歌曲:"+ma2.group(1));
										}
										try {
											LikedSongDownloader.down(coo, 100,
													pathtf.getText(), statel);
										} catch (NumberFormatException e) {
											JOptionPane.showMessageDialog(null, "请输入数字");
											e.printStackTrace();
										} catch (HttpException e) {
											e.printStackTrace();
										} catch (IOException e) {
											e.printStackTrace();
										} catch (InterruptedException e) {
											e.printStackTrace();
										} catch (NotSupportedException e) {
											e.printStackTrace();
										} catch (IllegalArgumentException e) {
											JOptionPane.showMessageDialog(null, e.getMessage());
										}
										statel.setText("达到最大尝试次数,请重新开始");
									}
								});
								t.start();
							}
						});
		browserb.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				fDialog = new JFileChooser(); // 文件选择器
				fDialog.setDialogTitle("请选择要导出目录");
				fDialog.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				int result = fDialog.showOpenDialog(frame);
				File file = null;
				if (JFileChooser.APPROVE_OPTION == result) {
					file = fDialog.getSelectedFile();
					if (!file.isDirectory()) {
						JOptionPane.showMessageDialog(null, "你选择的目录不存在");
						return;
					}
					String path = file.getAbsolutePath();
					pathtf.setText(path);
				}
			}
		});
		UserInfo info = null;
		if(new File("user.inf").exists()){
		try {
			info = new Gson().fromJson(FileUtils.readFileToString(new File("user.inf")), UserInfo.class);
		} catch (JsonSyntaxException e1) {
			e1.printStackTrace();
			LOG.error("用户信息文件解析错误");
		} catch (IOException e1) {
			e1.printStackTrace();
			LOG.equals("用户信息文件未找到");
		}
		usernametf.setText(info.getUsername());
		passwordtf.setText(new String(PasswordUtil.decrypt(info.getPassword().getBytes(), "940409")));
		pathtf.setText(info.getPath());
		}
	}
}
